package org.abettor.nookinfo.photo;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Random;

import org.abettor.nookinfo.AddressConstant;
import org.abettor.nookinfo.R;
import org.abettor.nookinfo.ads.YoumiManager;
import org.abettor.nookinfo.persist.PhotoHelper;
import org.abettor.nookinfo.view.OnPageJumpListener;
import org.abettor.nookinfo.view.PageDialog;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

/**
 * 本地图片列表
 * @author shawn
 *
 */
public class PhotoLocalList extends Activity
{
	private static final int MENU_PREV = Menu.FIRST + 1;
	private static final int MENU_NEXT = MENU_PREV + 1;
	private static final int MENU_JUMP = MENU_NEXT + 1;
	private static final int MENU_REFRESH = MENU_JUMP + 1;
	private static final int MENU_CLOSE = MENU_REFRESH + 1;
	private static final int THUMBNAIL_WIDTH = 100;
	private static final int THUMBNAIL_HEIGHT = 100;
	private float scaleRatio;
	private static final int PAGE_SIZE = 15;
	private static final int REFRESHED = 1;// 更新事件
	public static final String PHOTO_CATEGORY_ID = "__PHOTO_CATEGORY_ID";
	public static final String PHOTO_CATEGORY_NAME = "__PHOTO_CATEGORY_NAME";
	private YoumiManager youmi = new YoumiManager(this);
	private PhotoHelper photoHelper = new PhotoHelper(this);
	private int category;
	private List<Integer> imgList;
	private int totalPage = 0;
	private int currentPage = 1;
	private Handler handler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			if(msg.what == REFRESHED)
			{
				//	处理显示事件
				GridView grid = (GridView) findViewById(R.id.photoLocalList);
				grid.setOnItemClickListener(new ItemClickListener());
				PhotoViewAdapter adapter = new PhotoViewAdapter(PhotoLocalList.this);
				grid.setAdapter(adapter);
				adapter.notifyDataSetChanged();

				//	显示广告
				Random rand = new Random(System.currentTimeMillis());
				int val = rand.nextInt(99);
				if(val < 30)
				{
					youmi.showYoumi(YoumiManager.Position.top, Color.WHITE, Color.BLACK, 0xAA);
				}
			}

			super.handleMessage(msg);
		}
	};

	@Override
	public void onStart()
	{
		super.onStart();
		setContentView(R.layout.photo_local_list);
		Intent intent = getIntent();
		Bundle extras = intent.getExtras();
		category = extras.getInt(PHOTO_CATEGORY_ID);
		String categoryName = extras.getString(PHOTO_CATEGORY_NAME);
		String label = getString(R.string.photo_local_list_title).replace("REPL", categoryName);
		setTitle(label);
		totalPage = photoHelper.getPhotoPageCount(category, PAGE_SIZE);

		onUpdateClicked(null);

		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		scaleRatio = dm.density;
	}

	/**
	 * 创建Menu菜单
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		boolean result = super.onCreateOptionsMenu(menu);
		menu.add(0, MENU_PREV, MENU_PREV, getString(R.string.global_menu_prev)).setIcon(R.drawable.global_menu_prev);
		menu.add(0, MENU_NEXT, MENU_NEXT, getString(R.string.global_menu_next)).setIcon(R.drawable.global_menu_next);
		menu.add(0, MENU_JUMP, MENU_JUMP, getString(R.string.global_menu_jump)).setIcon(R.drawable.global_menu_jump);
		menu.add(0, MENU_REFRESH, MENU_REFRESH, getString(R.string.global_menu_refresh)).setIcon(R.drawable.global_menu_refresh);
		menu.add(0, MENU_CLOSE, MENU_CLOSE, getString(R.string.global_menu_close)).setIcon(R.drawable.global_menu_close);

		return result;
	}

	/**
	 * 处理菜单事件
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch(item.getItemId())
		{
		case MENU_PREV:
			onPrevClicked(null);
			break;
		case MENU_NEXT:
			onNextClicked(null);
			break;
		case MENU_JUMP:
			//	跳转到……
			PageDialog pageDialog = new PageDialog(this, totalPage, currentPage);
			pageDialog.setTitle(R.string.global_menu_jump);
			pageDialog.setOnPageJumpListener(new OnPageJumpListener()
			{
				@Override
				public void onPageJump(PageDialog dialog)
				{
					int current = dialog.getCurrentPage();
					if(current <= 0 || current > totalPage)
					{
						return;
					}

					currentPage = current;
					dialog.dismiss();
					onUpdateClicked(null);
				}
			});
			pageDialog.show();
			break;
		case MENU_REFRESH:
			onUpdateClicked(null);
			break;
		case MENU_CLOSE:
			onExitClicked(null);
			break;
		}

		return super.onOptionsItemSelected(item);
	}

	/**
	 * 刷新按钮
	 * @param v
	 */
	public void onUpdateClicked(View v)
	{
		Message msg = new Message();
		msg.what = REFRESHED;
		handler.sendMessage(msg);
	}

	/**
	 * 上一页
	 * @param v
	 */
	public void onPrevClicked(View v)
	{
		totalPage = photoHelper.getPhotoPageCount(category, PAGE_SIZE);
		if(totalPage == 0)
		{
			return;
		}

		currentPage --;
		if(currentPage <= 0)
		{
			currentPage = 1;
		}

		onUpdateClicked(null);
	}

	/**
	 * 下一页
	 * @param v
	 */
	public void onNextClicked(View v)
	{
		totalPage = photoHelper.getPhotoPageCount(category, PAGE_SIZE);
		if(totalPage == 0)
		{
			return;
		}

		currentPage ++;
		if(currentPage > totalPage)
		{
			currentPage = totalPage;
		}

		onUpdateClicked(null);
	}

	/**
	 * 返回按钮
	 * @param v
	 */
	public void onExitClicked(View v)
	{
		finish();
	}

	// 图片点击的监听器
	public class ItemClickListener implements AdapterView.OnItemClickListener
	{
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id)
		{
			Bundle extras = new Bundle();
			extras.putInt(PhotoLocalView.PHOTO_ID, imgList.get(position));
			Intent viewImageIntent = new Intent();
			viewImageIntent.putExtras(extras);
			viewImageIntent.setClass(PhotoLocalList.this, PhotoLocalView.class);
			startActivity(viewImageIntent);
		}
	}

	//	图片显示的适配器
	public class PhotoViewAdapter extends BaseAdapter
	{
		private Context context;

		public PhotoViewAdapter(Context context)
		{
			this.context = context;
			imgList = photoHelper.getPhotoList(category, PAGE_SIZE, currentPage);
		}

		@Override
		public int getCount()
		{
			return imgList.size();
		}

		@Override
		public Object getItem(int position)
		{
			return imgList.get(position);
		}

		@Override
		public long getItemId(int position)
		{
			return imgList.get(position).longValue();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
			ImageView imageView;
			if(convertView == null)
			{
				imageView = new ImageView(context);
				imageView.setLayoutParams(new GridView.LayoutParams((int) (THUMBNAIL_WIDTH * scaleRatio), (int) (THUMBNAIL_HEIGHT * scaleRatio)));
				imageView.setScaleType(ImageView.ScaleType.FIT_XY);
			}
			else
			{
				imageView = (ImageView) convertView;
			}

			InputStream is = null;
			try
			{
				String path = AddressConstant.PHOTO_THUMBNAIL_IMAGE_LOCAL.replace("ID", imgList.get(position).intValue() + "");
				File file = new File(path);
				if(file.exists())
				{
					is = new FileInputStream(file);
				}
				else
				{
					is = getResources().openRawResource(R.raw.thumbnail_failed);
				}
				Bitmap bitmap = BitmapFactory.decodeStream(is);
				imageView.setImageBitmap(bitmap);
				return imageView;
			}
			catch(Exception e)
			{
				Log.d(this.getClass().getName(), "", e);
			}
			finally
			{
				if(is != null)
				{
					try { is.close(); } catch (Exception e) { };
				}
			}

			return null;
		}
	}
}
